package com.situ.gym.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.situ.gym.pojo.User;
import com.situ.gym.pojo.query.UserQuery;
import com.situ.gym.service.IUserService;
import com.situ.gym.util.JwtUtil;
import com.situ.gym.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2025-08-22
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    //Restful    GET(查找)、POST(添加)、DELETE(删除)、PUT(修改)
    @GetMapping("/list")
    public Result<IPage<User>> list(UserQuery userQuery) {
        System.out.println("UserController.list");
        IPage<User> page = userService.list(userQuery);
        return Result.ok(page);
    }

    // /deleteById?id=1
    // /deleteById/1
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Long id) {
        userService.removeById(id);
        return Result.ok("删除成功");
    }

    // /deleteAll/1,2,3
    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Long[] ids) {
        userService.deleteAll(ids);
        return Result.ok("删除成功");
    }

    // @RequestBody : 封装前台传递过来的JSON格式数据
    // @ResponseBody : 将数据转换为JSON格式返回
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        System.out.println(user);
        userService.save(user);
        return Result.ok("添加成功");
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Long id) {
        User user = userService.getById(id);
        return Result.ok(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        System.out.println(user);
        userService.updateById(user);
        return Result.ok("更新成功");
    }

    @PutMapping("/updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        userService.updateById(user);
        return Result.ok("修改成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        System.out.println("用户登录请求 - 用户名: " + user.getName() + ", 密码: " + user.getPassword());
        
        // 根据用户名查询用户
        User loginUser = userService.selectByName(user.getName());
        System.out.println("查询到的用户: " + loginUser);
        
        if (loginUser == null) {
            System.out.println("用户名不存在: " + user.getName());
            return Result.error("用户名错误");
        }
        
        // 判断密码是否正确
        System.out.println("输入密码: " + user.getPassword() + ", 数据库密码: " + loginUser.getPassword());
        if (!user.getPassword().equals(loginUser.getPassword())) {
            System.out.println("密码不匹配");
            return Result.error("密码错误");
        }
        
        // 判断用户状态是否正常
        System.out.println("用户状态: " + loginUser.getStatus());
        if (loginUser.getStatus() == 0) {
            System.out.println("用户已被停用");
            return Result.error("用户已被停用");
        }

        // 登录成功
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginUser.getId());
        map.put("name", loginUser.getName());
        String token = JwtUtil.createToken(map);
        System.out.println("登录成功，生成token: " + token);
        return Result.ok("登录成功", token);
    }

    /**
     * 用户重置密码
     */
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody Map<String, String> passwordData) {
        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");
        
        // 从token中获取用户ID
        String token = passwordData.get("token");
        if (token == null) {
            return Result.error("未找到用户token");
        }
        
        Map<String, Object> claims = JwtUtil.parseToken(token);
        if (claims == null || claims.get("id") == null) {
            return Result.error("token无效");
        }
        
        Long userId = Long.valueOf(claims.get("id").toString());
        User user = userService.getById(userId);
        
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 验证旧密码
        if (!oldPassword.equals(user.getPassword())) {
            return Result.error("原密码错误");
        }
        
        // 更新密码
        user.setPassword(newPassword);
        userService.updateById(user);
        
        return Result.ok("密码修改成功");
    }
}